/*
    XHoldingPattern
    Copyright (C) 2009 Mike Gehl

    X-Plane Plugin SDK
    Copyright (C) Sandy Barbour and Ben Supnik

    This file is part of XHoldingPattern.

    XHoldingPattern is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    XHoldingPattern is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with XHoldingPattern.  If not, see <http://www.gnu.org/licenses/>.
    ---------------------------------------------------------------------------
    pattern.c
    Copyright (C) Mike Gehl 2009 <mjgehl@gmail.com>

    Routines to fly a holding pattern
*/

#include <math.h>
#include "pattern.h"

void update_position(double lat, double lon, PATTERN_DATA *pattern)
{
    pattern->plane_lat = lat;
    pattern->plane_lon = lon;

    double delta_lat = deg2rad(pattern->navaid_lat - pattern->plane_lat);
    double delta_lon = deg2rad(pattern->navaid_lon - pattern->plane_lon);
    double lat1 = deg2rad(pattern->plane_lat);
    double lat2 = deg2rad(pattern->navaid_lat);

    // source: http://williams.best.vwh.net/avform.htm
    double aa = pow(sin(delta_lat / 2), 2) +
                cos(lat1) * cos(lat2) *  pow(sin(delta_lon / 2), 2);

    double cc = 2 * atan2(sqrt(aa), sqrt(1 - aa));
    pattern->distance = pattern->radius * cc;
}

void pattern_intercept(PATTERN_DATA *pattern)
{
    double delta_lon = deg2rad(pattern->plane_lon - pattern->navaid_lon);
    double lat1 = deg2rad(pattern->plane_lat);
    double lat2 = deg2rad(pattern->navaid_lat);

    // source: http://williams.best.vwh.net/avform.htm
    double heading = fmod(atan2(sin(delta_lon)* cos(lat2),
                cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(delta_lon)),
                2 * M_PI);

   pattern->heading = trimHeading(rad2deg(-heading));
}


double deg2rad(double deg)
{
  return (deg * M_PI / 180);
}


double rad2deg(double rad)
{
  return (rad * 180 / M_PI);
}

double meters2miles(double meters)
{
    return (meters * METERS_TO_MILES);
}
